<template>
	<view class="dealer-container page-container">
		<!-- 经销商信息卡片 -->
		<view class="dealer-card" v-if="isDealer">
			<view class="store-info">
				<view class="store-header">
					<image :src="$tools.buildUrl(dealerInfo.shop_logo)" mode="aspectFill" class="store-logo"></image>
					<view class="store-details">
						<text class="store-name">{{ dealerInfo.shop_name }}</text>
						<text class="store-code">编号：{{ dealerInfo.company_id }}</text>
					</view>
				</view>
			</view>

			<view class="info-stats">
				<view class="stat-item">
					<text class="stat-number">{{ dealerExInfo.todaySales }}</text>
					<text class="stat-label">今日销量</text>
				</view>
				<view class="stat-item">
					<text class="stat-number">¥{{ dealerExInfo.todayAmount }}</text>
					<text class="stat-label">今日销售额</text>
				</view>
				<view class="stat-item">
					<text class="stat-number">{{ dealerExInfo.totalProducts }}</text>
					<text class="stat-label">在售商品</text>
				</view>
				<view class="stat-item">
					<text class="stat-number">{{ dealerExInfo.pendingOrders }}</text>
					<text class="stat-label">待处理订单</text>
				</view>
			</view>
		</view>

		<!-- 非经销商提示 -->
		<view v-else class="no-dealer-card">
			<view class="no-dealer-content">
				<text class="no-dealer-icon">🏪</text>
				<text class="no-dealer-title">您还不是经销商或经销商员工</text>
				<text class="no-dealer-desc">经销商由平台指定，如有疑问请联系客服</text>
			</view>
		</view>

		<!-- 快捷操作 -->
		<!-- <view v-if="isDealer" class="quick-actions">
			<view class="section-title">
				<text class="title-text">快捷操作</text>
			</view>
			<view class="actions-grid">
				<view 
					class="action-item" 
					v-for="(action, index) in quickActions" 
					:key="index"
					@click="handleActionClick(action)"
				>
					<view class="action-icon">
						<text class="action-emoji">{{ action.emoji }}</text>
					</view>
					<text class="action-name">{{ action.name }}</text>
					<view v-if="action.badge" class="action-badge">
						<text class="badge-text">{{ action.badge }}</text>
					</view>
				</view>
			</view>
		</view> -->

		<!-- 功能菜单 -->
		<view v-if="isDealer" class="function-grid">
			<view class="section-title">
				<text class="title-text">经销商管理</text>
			</view>
			<view class="grid-container">
				<view class="function-item" v-for="(item, index) in functionList" :key="index"
					@click="handleFunctionClick(item)">
					<view class="function-icon">
						<text class="function-emoji">{{ item.emoji }}</text>
					</view>
					<text class="function-name">{{ item.name }}</text>
					<view v-if="item.badge" class="function-badge">
						<text class="badge-text">{{ item.badge }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 小店推广卡片 -->
		<view v-if="isDealer" class="promotion-card">
			<view class="section-title">
				<text class="title-text">小店推广</text>
				<text class="subtitle-text">分享专属小程序码，邀请好友购买</text>
			</view>

			<view class="promotion-content">
				<view class="qrcode-container">
					<!-- <image :src="qrCodeUrl" mode="aspectFit" class="qrcode-image"></image> -->
					<canvas canvas-id="qrcode" :style="{ width: (size+40) + 'rpx', height: (size+40) + 'rpx' }"
						class="qr-canvas" />
					<text class="qrcode-label">专属小程序码</text>
				</view>

				<view class="promotion-actions">
					<button class="action-btn primary" open-type="share">
						<text class="btn-text">分享小店</text>
					</button>
					<view class="action-btn secondary" @click="downloadQRCode">
						<text class="btn-text">保存到相册</text>
					</view>
				</view>
			</view>
		</view>


	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex'
	import UQRCode from 'uqrcodejs';

	export default {
		data() {
			return {
				// 经销商状态
				isDealer: false, // 是否为经销商（由后台指定）
				dealerExInfo: {
					todaySales: 0,
					todayAmount: "0.00",
					totalProducts: 0,
					pendingOrders: 0,
				},
				// 推广链接
				size: 200, // 二维码大小
				promotionLink: "", // 专属小程序码（示例）
				// 快捷操作
				quickActions: [{
						name: "商品上架",
						emoji: "📦",
						action: "addProduct",
					},
					{
						name: "处理订单",
						emoji: "📋",
						action: "processOrder",
						badge: "0",
					},
					{
						name: "库存管理",
						emoji: "📊",
						action: "manageStock",
					},
					{
						name: "分享小店",
						emoji: "🔗",
						action: "shareStore",
					},
				],
				// 功能列表
				functionList: [{
						name: "小店管理",
						emoji: "🏪",
						path: "/dealer-package/store/list",
					},
					{
						name: '商品分类',
						emoji: '📊',
						path: '/dealer-package/product/category'
					},
					{
						name: "商品管理",
						emoji: "📦",
						path: "/dealer-package/product/list",
					},
					{
						name: "订单管理",
						emoji: "📋",
						path: "/dealer-package/order/list",
						badge: "0",
					},
					{
						name: "销量统计",
						emoji: "📈",
						path: "/dealer-package/statistics/overview",
					},
					{
						name: "热销排行",
						emoji: "🏆",
						path: "/dealer-package/product/ranking",
					},
					{
						name: "售后管理",
						emoji: "🛠️",
						path: "/dealer-package/order/after-sale",
						badge: "0",
					},
					{
						name: "订单核销",
						emoji: "📋",
						path: "/dealer-package/order/pickup",
					}
				],
			};
		},
		computed: {
			...mapGetters(['dealerInfo'])
		},

		mounted() {
			this.generateQRCode();
		},

		onLoad() {
			this.checkDealerStatus();
			this.loaddealerExInfo();
		},

		// 微信小程序分享配置
		onShareAppMessage() {
			const dealerCode = this.$secret.encryptAES(this.dealerInfo.company_id)
			let imageUrl = this.$tools.buildUrl('/static/images/product.png')
			if (this.dealerInfo && this.dealerInfo.shop_logo != '') {
				imageUrl = this.$tools.buildUrl(this.dealerInfo.shop_logo)
			}

			return {
				title: `${this.dealerInfo.shop_name} - 优质六堡茶专营`,
				path: `/pages/index/index?dealerCode=${dealerCode}`,
				imageUrl: imageUrl
			};
		},

		// 分享到朋友圈配置
		onShareTimeline() {
			const dealerCode = this.$secret.encryptAES(this.dealerInfo.company_id)
			let imageUrl = this.$tools.buildUrl('/static/images/product.png')
			if (this.dealerInfo && this.dealerInfo.shop_logo != '') {
				imageUrl = this.$tools.buildUrl(this.dealerInfo.shop_logo)
			}

			return {
				title: `${this.dealerInfo.shop_name} - 优质六堡茶专营`,
				query: `dealerCode=${dealerCode}`,
				imageUrl: imageUrl
			};
		},
		methods: {
			// 检查经销商状态
			checkDealerStatus() {
				// 从后台获取用户是否为经销商
				this.$api.agent.GetAgentShopInfo().then(res => {
					this.isDealer = true
					this.$store.dispatch('updateDealerInfo', res.data)
					const dealerCode = this.$secret.encryptAES(this.dealerInfo.company_id)
					this.promotionLink = 'http://www.gxwzlbc.com/invite?dealerCode=' + dealerCode;
					this.generateQRCode();
				})
			},

			loaddealerExInfo() {
				// 从后台获取经销商统计数据
				this.$api.agent.GetAgentShopExInfo().then(res => {
					this.dealerExInfo = res.data
					let orderitem = this.functionList.find(item => item.name === '订单管理')
					if (orderitem) {
						orderitem.badge = this.dealerExInfo.pendingOrders
					}

					let afteritem = this.functionList.find(item => item.name === '售后管理')
					if (afteritem) {
						afteritem.badge = this.dealerExInfo.afterOrders
					}
				})
			},

			// 处理快捷操作点击
			handleActionClick(action) {
				switch (action.action) {
					case "addProduct":
						uni.navigateTo({
							url: "/dealer-package/product/add",
						});
						break;
					case "processOrder":
						uni.navigateTo({
							url: "/dealer-package/order/list",
						});
						break;
					case "manageStock":
						uni.navigateTo({
							url: "/dealer-package/product/stock",
						});
						break;
					case "shareStore":
						this.shareStore();
						break;
				}
			},

			// 处理功能点击
			handleFunctionClick(item) {
				if (!this.isDealer) {
					uni.showToast({
						title: "您还不是经销商",
						icon: "none",
					});
					return;
				}

				if (item.path) {
					uni.navigateTo({
						url: item.path,
					});
				} else {
					uni.showToast({
						title: "功能开发中",
						icon: "none",
					});
				}
			},

			// 跳转到统计页面
			toStatistics() {
				uni.navigateTo({
					url: "/dealer-package/statistics/overview",
				});
			},

			generateQRCode() {
				if (!(this.promotionLink && this.promotionLink != '')) {
					return
				}
				const qr = new UQRCode();
				qr.data = this.promotionLink; // 二维码内容
				qr.size = 130; // 尺寸需与 canvas 一致
				qr.margin = 5;
				qr.foregroundColor = '#000000';
				qr.backgroundColor = '#FFFFFF';

				// 添加logo
				// 最佳实践：
				// 1. 尺寸：80×80像素
				// 2. 格式：PNG（带透明背景）
				// 3. 颜色：单色或简单双色
				let logoUrl = this.$tools.buildUrl('/static/images/product.png')
				if (this.dealerInfo && this.dealerInfo.shop_logo != '') {
					logoUrl = this.$tools.buildUrl(this.dealerInfo.shop_logo)
				}
				if (logoUrl && logoUrl != '') {
					qr.logo = logoUrl;
					qr.logoScale = 0.2; // logo占二维码比例										
				}

				qr.make(); // 生成二维码
				const ctx = uni.createCanvasContext('qrcode', this); // 组件需传 this
				qr.canvasContext = ctx;
				qr.drawCanvas();
			},

			downloadQRCode() {
				// 将Canvas转换为临时图片
				uni.canvasToTempFilePath({
					canvasId: 'qrcode',
					success: (res) => {
						this.tempFilePath = res.tempFilePath;
						uni.getSetting({
							success: (res2) => {
								if (!res2.authSetting['scope.writePhotosAlbum']) {
									// 申请权限
									uni.authorize({
										scope: 'scope.writePhotosAlbum',
										success: () => {
											this.saveImage(this.tempFilePath)
										}
									});
								} else {
									// 保存到相册
									this.saveImage(this.tempFilePath);
								};
							}
						});
					},
					fail: (err) => {
						console.error('转换失败:', err);
						uni.showToast({
							title: '生成图片失败',
							icon: 'none'
						});
					}
				}, this);
			},

			// 保存到相册
			saveImage(url) {
				uni.saveImageToPhotosAlbum({
					filePath: url,
					success: () => {
						uni.showToast({
							title: '保存成功'
						})
					},
					fail: () => {
						uni.showToast({
							title: '保存失败',
							icon: 'none'
						})
					}
				});
			},
		},
	};
</script>

<style lang="scss" scoped>
	.dealer-container {
		background-color: #f8f9fa;
		min-height: 100vh;
		padding: 20rpx;
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
	}

	/* 经销商信息卡片 */
	.dealer-card {
		background: linear-gradient(135deg, #52a58a 0%, #6bb6a3 100%);
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		color: white;
	}

	/* 非经销商提示卡片 */
	.no-dealer-card {
		background-color: white;
		border-radius: 20rpx;
		padding: 60rpx 30rpx;
		margin-bottom: 30rpx;
		text-align: center;
	}

	.no-dealer-content {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 20rpx;
	}

	.no-dealer-icon {
		font-size: 80rpx;
		margin-bottom: 10rpx;
	}

	.no-dealer-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
	}

	.no-dealer-desc {
		font-size: 26rpx;
		color: #666;
		line-height: 1.5;
	}

	.store-info {
		margin-bottom: 30rpx;
	}

	.store-header {
		display: flex;
		align-items: center;
		gap: 20rpx;
	}

	.store-logo {
		width: 80rpx;
		height: 80rpx;
		border-radius: 12rpx;
		border: 2rpx solid rgba(255, 255, 255, 0.3);
	}

	.store-details {
		flex: 1;
	}

	.store-name {
		font-size: 32rpx;
		font-weight: 600;
		display: block;
		margin-bottom: 8rpx;
	}

	.store-code {
		font-size: 24rpx;
		opacity: 0.8;
		display: block;
	}

	.info-stats {
		display: flex;
		justify-content: space-between;
	}

	.stat-item {
		text-align: center;
		flex: 1;
	}

	.stat-number {
		font-size: 36rpx;
		font-weight: 700;
		display: block;
		margin-bottom: 8rpx;
	}

	.stat-label {
		font-size: 24rpx;
		opacity: 0.8;
		display: block;
	}

	/* 快捷操作 */
	.quick-actions {
		background-color: white;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
	}

	.section-title {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.title-text {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
	}

	.more-link {
		font-size: 26rpx;
		color: #52a58a;
	}

	.actions-grid {
		display: flex;
		justify-content: space-between;
	}

	.action-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		position: relative;
		flex: 1;
	}

	.action-icon {
		width: 80rpx;
		height: 80rpx;
		background: linear-gradient(135deg, #52a58a 0%, #6bb6a3 100%);
		border-radius: 20rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 15rpx;
	}

	.action-emoji {
		font-size: 36rpx;
	}

	.action-name {
		font-size: 24rpx;
		color: #666;
		text-align: center;
	}

	.action-badge {
		position: absolute;
		top: -5rpx;
		right: 15rpx;
		background-color: #ff4757;
		color: white;
		border-radius: 20rpx;
		padding: 4rpx 8rpx;
		min-width: 20rpx;
		height: 20rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.badge-text {
		font-size: 20rpx;
		line-height: 1;
	}

	/* 功能菜单 */
	.function-grid {
		background-color: white;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
	}

	.grid-container {
		display: grid;
		grid-template-columns: repeat(4, 1fr);
		gap: 30rpx;
	}

	.function-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		position: relative;
	}

	.function-item.disabled {
		opacity: 0.5;
	}

	.function-icon {
		width: 80rpx;
		height: 80rpx;
		background-color: #f8f9fa;
		border-radius: 20rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 15rpx;
	}

	.function-emoji {
		font-size: 36rpx;
	}

	.function-name {
		font-size: 24rpx;
		color: #666;
		text-align: center;
	}

	.function-badge {
		position: absolute;
		top: -5rpx;
		right: 5rpx;
		background-color: #ff4757;
		color: white;
		border-radius: 20rpx;
		padding: 4rpx 8rpx;
		min-width: 20rpx;
		height: 20rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	/* 小店推广卡片 */
	.promotion-card {
		background-color: white;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
	}

	.subtitle-text {
		font-size: 24rpx;
		color: #999;
		margin-top: 8rpx;
		display: block;
	}

	.promotion-content {
		margin-top: 30rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 30rpx;
	}

	.qrcode-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 15rpx;
	}

	.qrcode-image {
		width: 200rpx;
		height: 200rpx;
		border-radius: 12rpx;
		border: 2rpx solid #f0f0f0;
	}

	.qrcode-label {
		font-size: 24rpx;
		color: #666;
		text-align: center;
	}

	.qr-canvas {
		/* 确保 Canvas 可见 */
		display: block;
		background: white;
	}

	.promotion-actions {
		display: flex;
		gap: 20rpx;
		width: 100%;
	}

	.action-btn {
		flex: 1;
		padding: 20rpx;
		border-radius: 12rpx;
		text-align: center;
		border: none;
		outline: none;
		font-size: inherit;
		line-height: inherit;
	}

	.action-btn.primary {
		background-color: #52a58a;
		color: white;
	}

	.action-btn.secondary {
		background-color: #f8f9fa;
		color: #333;
		border: 2rpx solid #e9ecef;
	}

	/* 重置 button 默认样式 */
	.action-btn::after {
		border: none;
	}

	.btn-text {
		font-size: 26rpx;
		font-weight: 500;
	}
</style>